<template>
	<div>
		<el-form
		style="margin-top:20px;"
		    :model="ruleForm"
		    ref="ruleForm"
		    :rules="rules"
		    :label-position="labelPosition"
		    label-width="120px"
		    class="demo-ruleForm "
		>
		    <el-row class="container">
				<el-page-header @back="goback" content="新增繁殖">
				</el-page-header>
				<div style="height:20px;"></div>
		        <el-col :span="12" >
		            <el-form-item label="种苗名称：" prop="breedName">
						<el-select v-model="ruleForm.breedName" value-key="id"  placeholder="" style="width:300px">
						    <el-option v-for="item in breedNameList" :key="item.id" :label="item.name" :value="item.name">{{item.name}}</el-option>
						</el-select>
		            </el-form-item>
		        </el-col>
				<el-col :span ="12">
					<el-form-item label="品种名称：" prop="seedName">
					    <el-input
					        placeholder="请输入内容"
					        v-model="ruleForm.seedName"
					        style="width:300px"
					    ></el-input>
					</el-form-item>
				</el-col>

				<el-col :span="12">
					<el-form-item label="养殖批号：" prop="batch">
					    <el-input placeholder="请输入" v-model="ruleForm.batch" style="width: 300px">
					        <template slot="append">
								<el-button @click="addBatch">自动生成</el-button>
					        </template>
					    </el-input>
					</el-form-item>
				</el-col>

		        <el-col :span="10">

					<el-form-item label="养殖日期：" prop="time">
					    <el-date-picker
					        v-model="ruleForm.time"
					        type="date"
					        value-format="yyyy-MM-dd"
					        placeholder="请选择"
					        style="width:300px"
					    ></el-date-picker>
					</el-form-item>

		        </el-col>

				<el-col :span="12">
					<el-form-item label="养殖负责人：">
						<template>
							<el-select
								v-model="principal"
								@change="choosePrincipal"
								style="width:300px"
								placeholder="请选择"
							>
								<el-option
									v-for="item in userList"
									:key="item.name"
									:label="item.name"
									:value="item"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
				</el-col>
				<el-col :span="10" style="mmargin-top:0px;">
					<el-form-item label="关联产品：">
						<template>
							<el-select
				                v-model="productId"
								@change = "selectProduct"
								value-key="id"
								style="width:300px"
								placeholder="请选择"
							>
								<el-option
									v-for="item in productList"
									:key="item.id"
									:label="item.title"
									:value="item"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="基地：">
						<template>
							<el-select
								v-model="breedBase"
								@change="chooseBreedBase"
								value-key="id"
								style="width:300px"
								placeholder="请选择"
							>
								<el-option
									v-for="item in baseList"
									:key="item.id"
									:label="item.name"
									:value="item"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
				</el-col>
				<el-col :span="10">
					<el-form-item label="养殖区域：">
						<template>
							<el-select
								v-model="soil"
								@change="chooseSoil"
								value-key="id"
								style="width:300px"
								placeholder="请选择"
							>
								<el-option
									v-for="item in soilList"
									:key="item.id"
									:label="item.name"
									:value="item"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
				</el-col>
				<el-col>
					<!-- <el-form-item label="编号类型：">
						<el-radio v-model="ruleForm.type" label="耳标" border>耳标</el-radio>
						<el-radio v-model="ruleForm.type" label="RFID" border>RFID</el-radio>
					</el-form-item> -->
					<el-form-item label="RFID：">
						<el-input placeholder="请输入" v-model="code" style="width: 300px">
						    <template slot="append">
						        <el-button @click="add">添加</el-button>
						    </template>
						</el-input>
						<el-upload
							class="upload-demo"
							ref="upload"
							accept=".txt"
							action="https://jsonplaceholder.typicode.com/posts/"
							:before-upload="beforeUpload"
							:default-file-list="this.fileList"
						  >
						  <el-button slot="trigger" size="small" type="primary">批量导入</el-button>
						</el-upload>
						<!-- <el-button>模板下载</el-button> -->
					</el-form-item>
					<el-table
					    :data="tableData"
					    border
					    style="margin-top:20px;"
					    ref="multipleTable"
					    header-cell-class-name="table-header"
					>
					    <el-table-column prop="time" sortable label="导入时间"></el-table-column>
					    <el-table-column prop="type" sortable label="编号类型"></el-table-column>
					    <el-table-column prop="code" sortable label="编号"></el-table-column>
					    <el-table-column prop="sex" sortable label="性别">
							<template slot-scope="scope">
								<el-select v-model="scope.row.sex" placeholder="请选择">
								    <el-option
								      v-for="item in sexlist"
								      :key="item.value"
								      :label="item.value"
								      :value="item.value">
								    </el-option>
								 </el-select>
							</template>
						</el-table-column>
					    <el-table-column sortable label="绑定设备">
					        <template slot-scope="scope">
								<el-button type="text">点击绑定</el-button>
							</template>
					    </el-table-column>
					    <el-table-column label="操作" width="150" align="center">
					        <template slot-scope="scope">

								<el-button
								    type="text"
									style="color: red;"
								    @click="handleDelete(scope.$index, scope.row)"
								>删除</el-button>
					        </template>
					    </el-table-column>
					</el-table>
				</el-col>
		    </el-row>
			<el-row class="container" style="margin-top:20px;">
				<h3>母源信息</h3>
				<el-form-item label="编号类型：" style="margin-top:20px;">
					<el-radio-group v-model="parentType" @change="gettype">
					    <el-radio label="RFID" border>RFID</el-radio>
					    <el-radio label="养殖批号" border>养殖批号</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="RFID：" v-if="parentType == 'RFID'">
					<el-input placeholder="请输入" v-model="parentCode" style="width: 300px">
					    <template slot="append">
							<el-button @click="addParent">添加</el-button>
						</template>
					</el-input>
					<el-upload
					  class="upload-demo"
					  action="https://jsonplaceholder.typicode.com/posts/"
					  :show-file-list="false"
					  :on-change="imgPreview"
					  :auto-upload="false">
					  <el-button slot="trigger" size="small" type="primary">批量导入</el-button>
					</el-upload>
					<!-- <el-button>模板下载</el-button> -->
				</el-form-item>
				<el-form-item label="养殖批号" v-if="parentType == '养殖批号'">
					<el-select
						v-model="parentCode"
						@change="addParent1"
						value-key="id"
						style="width:300px"
						placeholder="请选择"
					>
						<el-option
							v-for="item in batchList"
							:key="item.id"
							:label="item.batch"
							:value="item.batch">
						</el-option>
					</el-select>
				</el-form-item>
				<el-table
				    :data="tableData1"
				    border
				    style="margin-top:20px;"
				    ref="multipleTable"
				    header-cell-class-name="table-header"
				>
				    <el-table-column prop="time" sortable label="导入时间"></el-table-column>
				    <el-table-column prop="seedName" sortable label="品种名称"></el-table-column>
				    <el-table-column prop="batch" sortable label="养殖批号"></el-table-column>
				    <el-table-column prop="type" sortable label="编号类型"></el-table-column>
					<el-table-column prop="code" sortable label="编号"></el-table-column>
					<el-table-column prop="sex" sortable label="性别">
					   <template slot-scope="scope">
							<el-select v-model="scope.row.sex" placeholder="请选择">
								<el-option
								  v-for="item in sexlist"
								  :key="item.value"
								  :label="item.value"
								  :value="item.value">
								</el-option>
							</el-select>
						</template>
					</el-table-column>
				    <el-table-column label="操作" width="150" align="center">
				        <template slot-scope="scope">

							<el-button
							    type="text"
								style="color: red;"
							    @click="handleDelete1(scope.$index, scope.row)"
							>删除</el-button>
				        </template>
				    </el-table-column>
				</el-table>
				<!-- <el-pagination
				    layout="total, prev, pager, next, jumper"
				    :page-size="pagesize"
				    :current-page.sync="currentPage1"
				    :total="total1"
				    @current-change="handleCurrentChange1"
				    style="margin-top:20px"
				></el-pagination> -->
			</el-row>
		    <el-form-item class="footerFixed" label-width="0px">
		        <el-button type="primary" @click="submitrule('ruleForm')">提交</el-button>
		        <el-button @click="goback">取消</el-button>
		    </el-form-item>
		</el-form>
	</div>
</template>

<script>
import { soil_findAllBase,born_findById,born_save,born_findByTypeAndCode,born_inCode,soil_findSoilByType,breed_findBatchSelect,born_findByBatch } from '@/request/breedApi';
import { user_findByAll,basesource_findByAll,soil_findByBaseId,plot_findByAll,products_findByAll } from '@/request/api';
import {model_crop_loadbind} from "../../../../request/api";
	export default{
		data(){
			return{
				productId:'',
				sexlist:[
					{value:"雌"},
					{value:"雄"}
				],
				batchList:[],
				fileList:'',
				principal:"",
				breedBase:"",
				soil:"",
				code:"",
				parentType:"RFID",
				parentCode:"",
				tableData:[],
				tableData1:[],
				labelPosition:'right',
				ruleForm:{
					"batch":"",
					type:"RFID"
				},
				rules:{
					breedName: [{ required: true, message: '不能为空', trigger: 'change' }],
					batch: [{ required: true, message: '不能为空', trigger: 'change' }],
					seedName: [{ required: true, message: '不能为空', trigger: 'change' }],
					time: [{ required: true, message: '不能为空', trigger: 'change' }],
				},
				typeList:[],
				currentPage:1,
				currentPage1:1,
				total:0,
				total1:0,
				pagesize:10,
				breedNameList:[

				],
				userList:[],
				baseList:[],
				soilList:[]
			}
		},
		mounted() {
			this.init();
			this.init1()
		},
		methods:{
			init1(){
				products_findByAll("").then((res)=>{
					this.productList = res.data
				})
			},
			selectProduct(ele){
				this.ruleForm.productId = ele.id
			},
			gettype(){
				this.parentCode = ""
			},
			imgPreview(file,fileList){
				if(this.ruleForm.type == "" || this.ruleForm.type == null ||  this.ruleForm.type == undefined){
					this.$notify({
						title: '提示',
						message: '请选择编号类型后重新导入',
						type: 'info',
						duration:1000
					});
				}else{
					let data = {
						type:this.ruleForm.type,
						file:file.raw
					}
					let formdata = new FormData()
					for (var a in data) {
					    if (data[a] == null || data[a] == 'null') {
					        data[a] = '';
					        formdata.append(a, '');
					    } else {
					        formdata.append(a, data[a]);
					    }
					}
					born_inCode(formdata).then((res)=>{
						this.tableData = this.tableData.concat(res.data)
					})
				}
			},
			beforeUpload(file){
				this.fileList = [file]
				this.read(file);
				return false
			},
			read(f) {
				let rd = new FileReader();
				rd.onload = e => {
				//this.readAsArrayBuffer函数内，会回调this.onload函数。在这里处理结果
					let cont = rd.reading({encode: 'GBK'});
					let  formerData = this.textData;

					if(formerData == "" || formerData == null || formerData == undefined){
						this.textData = cont
					}else{
						this.textData = formerData + cont;
					}
					this.textData = this.textData.split("\r\n")

					var d=new Date();
					var year=d.getFullYear();
					var month=change(d.getMonth()+1);
					var day=change(d.getDate());
					var hour=change(d.getHours());
					var minute=change(d.getMinutes());
					var second=change(d.getSeconds());
					function change(t){
						if(t<10){
						return "0"+t;
						}else{
						return t;
						}
					}

					var time=year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;
					if(this.ruleForm.type == "" || this.ruleForm.type == null ||  this.ruleForm.type == undefined){
						this.$notify({
							title: '提示',
							message: '请选择编号类型后重新导入',
							type: 'info',
							duration:1000
						});
					}else{
						// console.log(this.textData)
						for(var i=0;i<this.textData.length;i++){
							console.log(this.textData[i])
							var params = {
								"time":time,
								"type":this.ruleForm.type,
								"code":this.textData[i],
								"sex":""
							}
							this.tableData.push(params);
						}
					}
					this.textData = ""
				};
				rd.readAsBinaryString(f);
			},
			init() {
				if (this.$route.query.id != undefined) {
					born_findById(this.$route.query.id).then((res) => {
						this.ruleForm = res.data;
						this.principal = res.data.principalName;
						this.breedBase = res.data.breedBaseName;
						this.soil = res.data.soilName;
						this.tableData = res.data.breedDetailList;
						this.tableData1 = res.data.parentDetailList;
					});
				}
				user_findByAll("").then((res) => {
					this.userList = res.data;
				});

				plot_findByAll("").then((res) => {
					this.baseList = res.data;
				});

        model_crop_loadbind("").then((res)=>{
				    this.breedNameList = res.data
				})
				breed_findBatchSelect("?souce=1").then((res)=>{
					this.batchList = res
				})
			},
			// 返回上一页
			goback(){
				this.$router.go(-1)
			},
			// 删除
			handleDelete(index,row){
				this.tableData.splice(index,1)
			},
			// 母源信息的删除
			handleDelete1(index,row){
				this.tableData1.splice(index,1)
			},
			handleCurrentChange(val) {
			    this.currentPage = val;
			},
			handleCurrentChange1(val) {
			    this.currentPage1 = val;
			},
			choosePrincipal(ele){
				this.ruleForm.principalId = ele.id;
				this.ruleForm.principalName = ele.name;
			},
			chooseBreedBase(ele) {
				this.ruleForm.breedBaseId = ele.id;
				this.ruleForm.breedBaseName = ele.name;
				soil_findByBaseId(`${ele.id}/2`).then((res)=>{
					this.soilList = res
				})
			},
			chooseSoil(ele) {
				this.ruleForm.soilId = ele.id;
				this.ruleForm.soilName = ele.name;
			},
			add() {
				if (this.code == "" || this.code == null) {
					this.$notify({
						title: '提示',
						message: '编号不能为空',
						type: 'info',
						duration:1000
					});
					return;
				}
				if (this.ruleForm.type == "" || this.ruleForm.type == null) {
					this.$notify({
						title: '提示',
						message: '编号类型不能为空',
						type: 'info',
						duration:1000
					});
					return;
				}
				var d=new Date();
				var year=d.getFullYear();
				var month=change(d.getMonth()+1);
				var day=change(d.getDate());
				var hour=change(d.getHours());
				var minute=change(d.getMinutes());
				var second=change(d.getSeconds());
				function change(t){
					if(t<10){
					return "0"+t;
					}else{
					return t;
					}
				}
				var time=year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;

				var params = {
					"time":time,
					"type":this.ruleForm.type,
					"code":this.code,
					"sex":""
				}
				this.tableData.push(params);
				this.code = "";
			},
			addParent() {
				//调用方法
				var params = {
					"type": this.parentType,
					"code": this.parentCode
				}
				born_findByTypeAndCode(params).then((res) => {
					if (res.code == 200) {
						this.tableData1.push(res.data);
					}
					this.parentCode = "";
				});
			},
			addParent1(){
				born_findByBatch(this.parentCode).then((res)=>{
					this.tableData1 = this.tableData1.concat(res.data)
					this.parentCode = "";
				})
			},
			addBatch() {
				var d = new Date();
				var curr_date = d.getDate();
				var curr_month = d.getMonth() + 1;
				var curr_year = d.getFullYear();
				String(curr_month).length < 2 ? (curr_month = "0" + curr_month): curr_month;
				String(curr_date).length < 2 ? (curr_date = "0" + curr_date): curr_date;
				var yyyyMMdd = curr_year + "" + curr_month +""+ curr_date;
				this.ruleForm.batch = yyyyMMdd + Math.ceil(Math.random()*10000);
			},
			//提交繁殖
			submitrule() {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.ruleForm.breedNumber = this.tableData.length;
						this.ruleForm.breedDetailList = this.tableData;
						this.ruleForm.parentDetailList = this.tableData1;
						born_save(this.ruleForm).then((res) => {
							if (res.code == 200) {
								this.$notify({
									title: '提示',
									message: '保存成功',
									type: 'success',
									duration:1000
								});
								this.goback()
							}
						});
					}else{
						return false
					}
				})
			}
		}
	}
</script>

<style scoped>
	.upload-demo{
		display:inline-block;
		margin-left:20px;
	}

	/deep/.el-upload--text{
		width:80px;
		height:35px;
	}
	.el-pagination {
	    text-align: center;
	}
	.el-dropdown-link {
	    cursor: pointer;
	    color: #409EFF;
	  }
	  .el-icon-arrow-down {
	    font-size: 12px;
	  }
	  .demonstration {
	    display: block;
	    color: #8492a6;
	    font-size: 14px;
	    margin-bottom: 20px;
	  }
</style>
